package com.yiyw.herostory.pipeline.Inbound;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import com.yiyw.herostory.factory.GameMsgProtocolFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author yiyw
 * @Description 消息解码器
 * @Date 2022/8/13 17:42
 **/
@Slf4j
public class GameMsgDecoder extends ChannelInboundHandlerAdapter {

    /***
     * Title: channelRead
     * @author yiyw
     * @description 收到消息事件
     * @createTime 2022/8/13 17:42
     * @param ctx   channel 上下文
     * @param msg   消息内容
     * @return void
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof BinaryWebSocketFrame) {
            BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
            ByteBuf byteBuf = frame.content();
            // 读取消息头第一个字节
            byteBuf.readShort();
            // 读取消息头第二个字节 -- 消息类型
            int msgType = byteBuf.readShort();

            GeneratedMessageV3 protocol = GameMsgProtocolFactory.getGameMsgProtocolByMsgCode(msgType);
            if (null == protocol) {
                return;
            }

            // 读取消息体
            byte[] msgBody = new byte[byteBuf.readableBytes()];
            // 读取到字节数组中
            byteBuf.readBytes(msgBody);

            Message.Builder builder = protocol.newBuilderForType();
            builder.mergeFrom(msgBody);
            ctx.fireChannelRead(builder.build());

        }
    }
}
